package com.situ.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.web.entity.User;

public class LgoinFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("LgoinFilter.doFilter()");
		//判断有没有登录
		//1、如果没有登录，重定向到登录界面
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		String uri = httpServletRequest.getRequestURI();
		System.out.println("uri: " + uri);
		String servletPath = httpServletRequest.getServletPath();
		System.out.println("servletPath: " + servletPath);
		// uri: /Java1812Web/login.jsp
		// servletPath: /login.jsp
		
		HttpSession session = httpServletRequest.getSession();
		User user = (User) session.getAttribute("user");
		// 特殊请求不需要验证是否登录
		if ("/login.jsp".equals(servletPath) 
				|| "/checkImg".equals(servletPath) 
				|| "/login".equals(servletPath)
				|| "/logout".equals(servletPath)
				|| servletPath.contains(".js")
				|| servletPath.contains(".css")
				|| servletPath.contains(".png")) {
			chain.doFilter(request, response);
		} else {
			/*if (user == null) {
				// 用户没有登录，重定向到登录界面
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login.jsp");
				return;
			}*/
			// 2、如果登录上，chain.doFilter()
			chain.doFilter(httpServletRequest, httpServletResponse);
		}
		
	}

	@Override
	public void destroy() {
	}
}
